package homework;

/**
 * SupperArray
 *
 * @author byc
 * @date 2021-09-12
 */
public class SupperArray {

    //存放data的数组
    int[] element;
    //维护当前存储的位置
    private int currentIndex = -1;
    //使用构造器初始化
    public SupperArray(){
        this(10);
    }
    public SupperArray(int capacity){
        element = new int[capacity];
    }

    //增
    public void add(int index,int data){
        //游标向前走
        currentIndex++;
        if (currentIndex > element.length - 2){
            int[] temp = new int[element.length * 2];
            for (int i = 0; i < element.length; i++) {
                temp[i] = element[i];
            }
            element = temp;
        }

        //移动位置 腾出空间
        for (int i = currentIndex; i >= index; i--) {
            element[i+1] = element[i];
        }
        element[index] = data;
    }

    //头插
    public void addToHead(int data){
        this.add(0,data);
    }
    //尾插
    public void addToTail(int data){
        this.add(currentIndex + 1,data);
    }
    //删
    public void delete(int index){
        if (index < 0 || index > element.length - 1){
            System.out.println("下标不再范围内。");
        }else {
            for (int i = index + 1; i < element.length; i++) {
                element[i - 1] = element[i];
            }
            currentIndex --;
        }
    }

    //改
    public void set(int index,int data){
        if (index < 0 || index > element.length - 1){
            System.out.println("下标不再范围内。");
        }else {
            element[index] = data;
        }
    }

    //查
    public Integer select(int index) {
        if (index < 0 || index > element.length - 1) {
            System.out.println("下标不再范围内。");
            return null;
        }else {
            return element[index];
        }
    }

    //获取长度
    public int size(){
        return currentIndex + 1;
    }

    //把数组变成字符转
    public String arrayToString(){
        String result = "[";
        for (int i = 0; i <= currentIndex; i++) {
            result += element[i] + ",";
        }
        return result.substring(0,result.length()-1) + "]";
    }

    //排序
    public void sort(){
        for (int i = 0; i < currentIndex; i++) {
            for (int j = 0; j < currentIndex; j++) {
                if (element[j] > element[j+1]){
                    int temp = element[j];
                    element[j] = element[j+1];
                    element[j+1] = temp;
                }
            }
        }
    }

}
